package com.wisenet.controller.client.wxpubno;

import com.alibaba.fastjson.JSONObject;
import com.wisenet.annotation.LoginValidate;
import com.wisenet.cache.SimpleCacheProvider;
import com.wisenet.common.WxConst;
import com.wisenet.controller.PlatformController;
import com.wisenet.entity.WeixinPubno;
import com.wisenet.wx.util.WeixinUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * 微信登录控制类
 * @author fzh
 */
@RestController
@RequestMapping("/wxlogin")
public class MiniAppLoginController extends PlatformController {
	@Autowired
	private SimpleCacheProvider simpleCacheProvider;

	/**
	 * 小程序登录
	 * @param jscode
	 * @param appid
	 * @return
	 */
	@LoginValidate(value = false)
	@RequestMapping("/jscodeLogin")
	public JSONObject login(String jscode, String appid) {
		JSONObject json = getJsonResult(jscode, appid);
		if (json.getBoolean(SUCCESS)) {
			WeixinPubno weixinPubno = simpleCacheProvider.get(appid);
			if (weixinPubno == null) {
				json.put(SUCCESS, false);
				json.put(MESSAGE, "APP不存在");
				return json;
			}
			String requestUrl = String.format(WxConst.JSCODE2SESSION_URL, 
					weixinPubno.getAppid(), weixinPubno.getAppsecret(), jscode);
			json = WeixinUtil.httpRequest(requestUrl, "POST", null);
			if (json != null && json.containsKey("session_key")) {
				json.put(SUCCESS, true);
				json.remove("session_key");
			}
		}
		return json;
	}
	
	/**
	 * QQ小程序
	 * @param jscode
	 * @param appid
	 * @return
	 */
	@LoginValidate(value = false)
	@RequestMapping(value = "/qq", method = RequestMethod.POST)
	public JSONObject getOpenIdByQQ(String jscode, String appid) {
		JSONObject json = getJsonResult(jscode, appid);
		if (json.getBoolean(SUCCESS)) {
			WeixinPubno weixinPubno = simpleCacheProvider.get(appid);
			if (weixinPubno == null) {
				json.put(SUCCESS, false);
				json.put(MESSAGE, "APP不存在");
				return json;
			}
			String requestUrl = String.format(WxConst.JSCODE2SESSION_URL_QQ, 
					weixinPubno.getAppid(), weixinPubno.getAppsecret(), jscode);
			json = WeixinUtil.httpRequest(requestUrl, "POST", null);
			if (json != null && json.containsKey("session_key")) {
				json.put(SUCCESS, true);
				json.remove("session_key");
			}
		}
		return json;
	}

	@Override
	protected String getBasePath() {
		return null;
	}

}
